import CryptoJS from 'crypto-js'

const AES_KEY = 'keppel@iot@2023#'
export default {
  // 解密  data：要加密解密的数据，AES_KEY：密钥，IV:偏移量
  aes_decrypt (data, key) {
    const _AES_KEY = key || AES_KEY
    const decrypt = CryptoJS.AES.decrypt(
      data,
      CryptoJS.enc.Utf8.parse(_AES_KEY),
      { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }
    )
    return decrypt.toString(CryptoJS.enc.Utf8)
  },
  // 加密
  aes_encrypt (data, key) {
    const _AES_KEY = key || AES_KEY
    const encrypted = CryptoJS.AES.encrypt(
      CryptoJS.enc.Utf8.parse(data),
      CryptoJS.enc.Utf8.parse(_AES_KEY),
      { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }
    )
    return encrypted.toString()
  },
  // MD5加密
  md5_encrypt (data) {
    return CryptoJS.MD5(data).toString()
  },
  // 解密  data：要加密解密的数据，AES_KEY：密钥，IV:偏移量
  session_decrypt (data, key) {
    const _AES_KEY = key || AES_KEY
    const decrypt = CryptoJS.AES.decrypt(
      data,
      this.md5_encrypt(_AES_KEY),
      { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }
    )
    return decrypt.toString(CryptoJS.enc.Utf8)
  },
  // 加密
  session_encrypt (data, key) {
    const _AES_KEY = key || AES_KEY
    const encrypted = CryptoJS.AES.encrypt(
      CryptoJS.enc.Utf8.parse(data),
      this.md5_encrypt(_AES_KEY),
      { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }
    )
    return encrypted.toString()
  }
}
